import os

from typing import Annotated, BinaryIO

from fastapi import Depends
from src.config.settings import settings


class StaticStorageService:

    def __init__(self):

        self.contents_dir = settings.CONTENTS_DIR

    def save_file(self, file: BinaryIO, filename: str):

        target_dir = os.path.join(
            self.contents_dir, *(filename.split("/")[:-1]))
        file_path = self._get_file_path(filename)

        if not os.path.exists(target_dir):
            os.makedirs(target_dir)

        with open(file_path, 'wb') as f:
            f.write(file.read())

    def fetch_file(self, filename: str) -> str:

        return self._get_file_path(filename)

    def delete_file(self, filename: str):

        file_path = self._get_file_path(filename)
        if os.path.exists(file_path):
            os.remove(file_path)

    def _get_file_path(self, filename: str) -> str:

        return os.path.join(self.contents_dir, filename)


def get_static_storage_service():

    return StaticStorageService()


StaticStorageServiceDep = Annotated[StaticStorageService, Depends(
    get_static_storage_service)]
